package com.zhkj.txg.module.home.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import com.zhihu.matisse.Matisse
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.txg.R
import com.zhkj.txg.module.home.entity.ApplyEntity
import com.zhkj.txg.module.home.popup.SelectedGenderDialog
import com.zhkj.txg.module.home.vm.MerchantViewModel
import com.zhkj.txg.utils.ImageUtils
import com.zhkj.txg.utils.MatisseUtils
import kotlinx.android.synthetic.main.activity_merchant_register.*
import razerdp.util.KeyboardUtils

class MerchantRegisterActivity : ViewModelActivity<MerchantViewModel>() {

    companion object {
        val TYPE_APPLY = "apply"
        fun open(activity: Activity, entity: ApplyEntity) {
            val intent = Intent(activity, MerchantRegisterActivity::class.java).putExtra(TYPE_APPLY, entity)
            activity.startActivity(intent)
        }
    }

    override fun setViewModel(): MerchantViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleMerchant
    override val layoutResId: Int = R.layout.activity_merchant_register

    private val requestCodeLicense = 1000
    private val requestCodeIdentifyFront = 1001
    private val requestCodeIdentifyBack = 1002

    private val genderDialog: SelectedGenderDialog by lazy {
        SelectedGenderDialog(this) {
            viewModel.gender = if (it) 1 else 2
            tvMerchantGender.text = getString(if (it) R.string.man else R.string.women)
        }
    }

    override fun initUI() {
        // 选择营业执照上传
        ivMerchantLicense.setOnClickListener {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, {
                selectPicture(requestCodeLicense)
            }, { toast(getString(R.string.read_permission_deny)) })
        }
        // 选择身份证正面上传
        ivMerchantIdentifyFront.setOnClickListener {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, {
                selectPicture(requestCodeIdentifyFront)
            }, { toast(getString(R.string.read_permission_deny)) })
        }
        // 选择身份证反面上传
        ivMerchantIdentifyBack.setOnClickListener {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, {
                selectPicture(requestCodeIdentifyBack)
            }, { toast(getString(R.string.read_permission_deny)) })
        }
        // 选择性别
        tvMerchantGender.setOnClickListener {
            if (KeyboardUtils.isOpen()) KeyboardUtils.close(this)
            genderDialog.showPopupWindow()
        }
        tvRule.setOnClickListener {
            WelfareActivity.merchant(this, tvRule.text.toString())
        }
        // 提交按钮监听
        tvMerchantSubmit.setOnClickListener {
            if (etMerchantName.text.isNullOrEmpty()) {
                toast(getString(R.string.merchant_name_hint))
                return@setOnClickListener
            }
            if (etMerchantAge.text.isNullOrEmpty()) {
                toast(getString(R.string.merchant_age_hint))
                return@setOnClickListener
            }
            if (etMerchantMobile.text.isNullOrEmpty()) {
                toast(getString(R.string.merchant_mobile_hint))
                return@setOnClickListener
            }
            if (etMerchantReason.text.isNullOrEmpty()) {
                toast(getString(R.string.merchant_reason_hint))
                return@setOnClickListener
            }
            if (viewModel.licenseEntity.filePath.isNullOrEmpty()) {
                toast(getString(R.string.upload_license))
                return@setOnClickListener
            }
            if (viewModel.identifyFrontEntity.filePath.isNullOrEmpty()) {
                toast(getString(R.string.upload_front))
                return@setOnClickListener
            }
            if (viewModel.identifyBackEntity.filePath.isNullOrEmpty()) {
                toast(getString(R.string.upload_front))
                return@setOnClickListener
            }
            viewModel.merchantRegister(
                AccountManager.getToken(), etMerchantName.text.toString(),
                etMerchantAge.text.toString(), etMerchantMobile.text.toString(),
                etMerchantReason.text.toString()
            )
        }
    }

    override fun initViewModel() {
        viewModel.registerLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                toast(getString(R.string.merchant_register_success))
                finish()
            }
        })
        viewModel.uploadLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
        })
    }

    override fun initData() {
        val status = intent.getSerializableExtra(TYPE_APPLY) as ApplyEntity
        if (status.isApply == true) {
            viewStatus.visibility = View.VISIBLE
            viewMerchant.visibility = View.GONE
            titleMerchant.showRight(false)
            tvStatus.text = getString(
                when (status.status) {
                    1 -> R.string.status_success
                    2 -> R.string.status_failure
                    else -> R.string.status_ing
                }
            )
            tvStatus.setCompoundDrawables(
                null, getDrawable(
                    when (status.status) {
                        1 -> R.drawable.ic_status_success
                        2 -> R.drawable.ic_status_failure
                        else -> R.drawable.ic_status_ing
                    }
                )?.apply {
                    setBounds(0, 0, intrinsicWidth, intrinsicHeight)
                }, null, null
            )
            tvReason.text = status.reason
        } else {
            titleMerchant.showRight(true).setRightClickListener(View.OnClickListener {
//                VP53Manager.getInstance().EnterChatActivity(KF_53_ARG, "1", this, null)
            })
            viewStatus.visibility = View.GONE
            viewMerchant.visibility = View.VISIBLE
        }
        viewModel.licenseEntity.filePath?.let {
            ImageUtils.loadRoundCornerImage(this, ivMerchantLicense, it)
        }
        viewModel.identifyFrontEntity.filePath?.let {
            ImageUtils.loadRoundCornerImage(this, ivMerchantIdentifyFront, it)
        }
        viewModel.identifyBackEntity.filePath?.let {
            ImageUtils.loadRoundCornerImage(this, ivMerchantIdentifyBack, it)
        }
        tvMerchantGender.text =
            getString(if (viewModel.gender == 1) R.string.man else R.string.women)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) Matisse.obtainPathResult(data).takeIf {
            it.isNotEmpty()
        }?.run {
            when (requestCode) {
                requestCodeLicense -> viewModel.licenseEntity
                requestCodeIdentifyFront -> viewModel.identifyFrontEntity
                requestCodeIdentifyBack -> viewModel.identifyBackEntity
                else -> null
            }?.apply {
                filePath = get(0)
            }
        }.let { path ->
            when (requestCode) {
                requestCodeLicense -> ivMerchantLicense
                requestCodeIdentifyFront -> ivMerchantIdentifyFront
                requestCodeIdentifyBack -> ivMerchantIdentifyBack
                else -> null
            }?.let {
                ImageUtils.loadRoundCornerImage(this, it, path?.filePath ?: "")
            }
        }
    }

    /**
     * 打开图片选择器
     */
    private fun selectPicture(requestCode: Int) {
        MatisseUtils.selectPicture(this, requestCode)
    }
}